package com.xs.ahoi.hcxs.service;

import android.content.Context;
import android.media.AudioManager;
import com.xs.ahoi.hcxs.utils.LogUtil;

import static android.content.Context.AUDIO_SERVICE;

/**
 * author: ahoi
 * date: 2018/8/21 13:38
 * description: 媒体焦点管理
 */
public class AudioFocusManager implements AudioManager.OnAudioFocusChangeListener {

    private final Context context;

    private final AudioManager mAudioManager;

    public AudioFocusManager(Context context) {
        this.context = context;
        this.mAudioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
    }

    // 播放音乐前先请求音频焦点
    public boolean requestAudioFocus() {
        int focus = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        return focus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
    }

    // 退出播放器后不再占用音频焦点
    public void throwAudioFocus() {
        mAudioManager.abandonAudioFocus(this);
    }

    /**
     * 音频焦点监听回调
     */
    @Override
    public void onAudioFocusChange(int focusChange) {
        BookFactory bookFactory = BookFactory.getInstance();
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN:
                // 重新获得焦点，可做恢复播放，恢复后台音量的操作
                LogUtil.e("重新获得焦点，恢复播放");
                bookFactory.startPlayIfNotPlay();
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                // 永久丢失焦点除非重新主动获取，这种情况是被其他播放器抢去了焦点，  为避免与其他播放器混音，可将音乐暂停
                LogUtil.e("被其他播放器抢去了焦点，暂时pause");
                bookFactory.stopPlay(false);
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                // 暂时丢失焦点，这种情况是被其他应用申请了短暂的焦点，可压低后台音量
                LogUtil.e("其他应用申请了短暂的焦点，暂时pause");
                bookFactory.stopPlay(false);
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                // 短暂丢失焦点，这种情况是被其他应用申请了短暂的焦点希望其他声音能压低音量（或者关闭声音）凸显这个声音（比如短信提示音），
                LogUtil.e("短暂丢失焦点，暂时pause");
                bookFactory.stopPlay(false);
                break;
        }
    }


}
